/*
 * @Description: 按钮操作相关一些共用函数
 */
/*global getCtpTop, _ctxPath, CsrfGuard, _getZWIframe, workflowModule, callBackendMethod*/
import {useTemplateWithOut} from '@/store/modules/template';
import {useBaseInfoWithOut} from '@/store/modules/base-info';
import {getQueryString, getTimestamp} from '@/plugins/methods';
import getFormData from "@/helper/form-params-helper";


//所有的操作集合
import handleObj from '@/handles/handle-list/create';
import errHandle from '@/handles/common/err-handle';
import closeWindow from '@/helper/close';
import api from '@/api';
import globalMethods from '@/plugins/methods';
import globalData, {BodyTypeEnums} from '@/plugins/data';
import zwIframe from '@/components/zw-iframe/index.vue';


const useTemplate = useTemplateWithOut();
const useBaseInfo = useBaseInfoWithOut();

//看逻辑是需要确认身份，确认了身份之后，选择的ID不等于工作流发起部门的id。
//就会执行保存待发操作。这个时候就不会再执行选部门操作了

export default {
  //协同主表唯一标识
  summaryId: getQueryString('summaryId'),
  //模板ID
  templateId: getQueryString('templateId'),
  //affairId
  affairId: getQueryString('affairId'),
  //基础信息store
  useBaseInfo,
  //下面表单区域
  useTemplate,

  /**
     * @description: 确认流程发起部门
     * 发起人存在兼职、副岗（需要相关人员进行说明），提交时确认以哪种身份发起数据。
        remind_workflow_start_department_id字段需要后端提供。为0的时候，就需要弹窗选择以什么身份操作
     * @param {Function} resolve 取消之后，就退出发送流程
     * @param {Function} callbackFunction 回调
     */
  confirmWorkflowStartDepartment(resolve, callbackFunction) {
    const { other } = useBaseInfo.baseInfo.businessData;
    if (other?.remindWorkflowStartDepartmentId === '0') {
      const dialog = globalMethods.dialog({
        id: 'saveAsTemplate',
        bodyStyle:'padding:0',
        url: `${_ctxPath}/personalAffair.do?method=confirmWorkflowStartDepartment${CsrfGuard.getUrlSurffix()}`,
        width: 400,
        height: 180,
        title: $.i18n('workflow.start.department.confirm.title'), // 另存为个人模板
        onCancel() {
          dialog.close();
          resolve();
        },
        onConfirm() {
          const new_wf_start_department_id = dialog.getValue();
          console.log(new_wf_start_department_id);

          //新选的工作流发起部门ID。←自己的理解
          if (!new_wf_start_department_id) {
            return;
          } else {
            dialog.close();
            other.remindWorkflowStartDepartmentId = '1';
            //新选的工作流发起部门ID不等于原来的。←自己的理解
            if (new_wf_start_department_id != other.workflowStartDepartmentId) {
              //保存待发
              handleObj.saveWaitSend();
            } else {
              callbackFunction();
            }
          }
        }
      });
    } else {
      callbackFunction();
    }
  },
  /**
   * @description: 创建最终提交的参数
   * @param submitOptType 提交类型：send saveAs saveAsTemplate 发送、保持待发、存为模版
   * @param needCheck {string|Object} contentObj 调用表单提交/预提交后返回的数据
   * @param checkProcess params 一些直接设置的参数
   * @return {Object}最终提交给接口的数据
   */
  async getCreateParams(submitOptType='send',needCheck = true, checkProcess = true) {
    let result = {
      status: false,
      params: {}
    };
    //协同主数据
    let colMainData = this.createColMainData();

    const baseInfo = useBaseInfo.baseInfo;

    //顺便更新一下工作流里面的密级 V5-17730
    workflowModule.setParam({ secretLevel: baseInfo.secretLevel.value });
    let workflowParamData = workflowModule.getWorkflowParams();
    //工作流数据
    if (checkProcess && !useBaseInfo.validateProcess(checkProcess)) {
      return result;
    }
    const businessData = baseInfo.businessData;
    const urlParam = baseInfo.businessData.urlParam;
    const template = baseInfo.businessData.template || {};
    const affair = baseInfo.businessData.affair;
    colMainData = Object.assign(baseInfo.collaborationSubmitData.colMainData, colMainData);
    let cap4 = useBaseInfo.baseInfo.zwIframe.isCap4;
    if (cap4) {
      // 表单数据
      let params = {
        checkNull: needCheck,
        needCheckRule: needCheck
      };
      const formData = await getFormData(params);
      //获取表单数据失败
      if (!formData) {
        return result;
      }
      formData.content.isMerge = '1';
      formData.content.needAutoCollect = '1';
      //TODO 
      formData.content.optType = submitOptType;
      formData.content.needCheckRule = '1';
      // 如果不需要表单校验
      if (!needCheck) {
        formData.content.needCheckRule = '0';
      }
      //设置formDataId
      colMainData.formRecordId = formData.content.contentDataId;
      const {
        processTemplateId=''
      } = useBaseInfo.baseInfo?.businessData?.workflow||{};
      //表单数据、formData，mastrid 在cap4 是同一个值
      workflowParamData.context.formData = formData.content.contentDataId;
      workflowParamData.context.mastrid = formData.content.contentDataId;
      workflowParamData.context.isCAP4 = true;
      workflowParamData.context.processTemplateId = processTemplateId;
      //表单数据
      result.params.formParamData = {
        data: formData
      };
    }
    //应用名称：一般为 collaboration 或者edoc
    workflowParamData.context.appName = 'collaboration';

    const otherParamData = {
      from: urlParam.from,
      subState: affair.subState,
      state: affair.state,
      affair: affair.id,
      reqFrom: urlParam.reqFrom
    };

    //协同数据？？？
    const thirdpartParamData = {
      beforeEventBO: {},
      data: [],
      thirdPartyContext: useBaseInfo.thirdPartyContext
    };

    //流程数据
    const workflowDefinition = {
      processDescBy: '',
      caseId: businessData.workflow.caseId,
      processId: businessData.workflow.processId,
      workflowNodeConditionInput: '',
      workflowNodePeoplesInput: '',
      processRuleContent: '',
      workflowNewFlowInput: '',
      moduleType: '1',
      processSubsetting: '',
      processInfoSelectvalue: '',
      processInfo: '',
      readyObjectJSON: '',
      processXml: workflowParamData.context.processXml || businessData?.workflow?.xml,
      processChangeMessage: workflowModule.getProcessChangeMessage(), //加签等
      processMessageData: '',
      currentNodeId: businessData.workflow.activityId,
      subObjectId: businessData.workflow.itemId,
      workflowThisNodeLastInput: '',
      workflowLastInput: '',
      dynamicFormMasterIds: '',
      toReGo: 'false',
      processProperties: '',
      processEvent: '',
      newGenerateOtherNodeIds: workflowModule.getNewGenerateOtherNodeIds(), //加签
      newGenerateNodeId: workflowModule.getNewGenerateNodeId(), //加签
      workflowDataFlag: 'WORKFLOW_SEEYON'
      // ...businessData.workflow,
    };

    //关联文档数据
    const assDocDomain = useBaseInfo.relationDocs.atts;
    assDocDomain &&
      assDocDomain.forEach((i) => {
        // 兼容createdate 和 createDate
        i.createDate
          ? i.createDate.split(' ').length > 1 && (i.createDate = getTimestamp(i.createDate))
          : i.createdate.split(' ').length > 1 && (i.createdate = getTimestamp(i.createdate));
      });

    //附件数据
    const attFileDomain = useBaseInfo.attachments.atts;
    attFileDomain &&
      attFileDomain.forEach((i) => {
        // 兼容createdate 和 createDate
        i.createDate
          ? i.createDate.split(' ').length > 1 && (i.createDate = getTimestamp(i.createDate))
          : i.createdate.split(' ').length > 1 && (i.createdate = getTimestamp(i.createdate));
      });

    //附言数据
    let commentDeal = {
      content: useBaseInfo.postscript
    };

    //如果有传过来的参数就设置
    if (baseInfo.collaborationSubmitData.commentDeal) {
      commentDeal = Object.assign(baseInfo.collaborationSubmitData.commentDeal, commentDeal);
    }
    const collaborationParamData = {
      commentDeal,
      workflowDefinition,
      assDocDomain,
      attFileDomain,
      colMainData
    };

    // 返回
    result.status = true;
    result.params = {
      ...result.params,
      collaborationParamData,
      workflowParamData,
      otherParamData,
      thirdpartParamData
    };

    return result;
  },
  /**
   * @description: 协同发送
   * @return {Object}最终提交给接口的数据
   */
  async send({ resolve, needCheck = true, weekSubmit = false }) {
    let { status, params } = await this.getCreateParams('send',needCheck);
    if (!status) {
      resolve();
      return;
    }
    //调处理界面的时候，后端让加上这个参数
    params.submitCode = 'Send';
    //dee弱校验不阻塞的
    if (params.workflowParamData) {
      params.workflowParamData.weekSubmit = weekSubmit;
    }
    let cap4 = useBaseInfo.baseInfo.zwIframe.isCap4;
    return new Promise((resolveCallBack, reject) => {
      if (!cap4) {
        const {id,bodyType} = useBaseInfo.baseInfo.businessData.summary;
        let getZWIframe = _getZWIframe();
        if (getZWIframe.document) {
          getZWIframe.document.getElementById('moduleId').value = id;
          if (`${bodyType}` === BodyTypeEnums.pdf.toString()) {
            const {affair} = useBaseInfo.baseInfo?.businessData || {};
            //待发事项数据id保持当前的
            if (affair.state !== 1) {
              getZWIframe.document.getElementById('contentDataId').value = globalMethods.getUUID();
            }
          }
          getZWIframe.document.getElementById('id').value = '';
        }
        getZWIframe.contentAPI.submit({
          checkNull: needCheck,
          mainbodyDomains: [],
          needCheckRepeatData: needCheck,
          needCheckRule: needCheck,
          needSn: needCheck,
          needSubmit: true,
          optType: 'send',
          summaryId: id,
          failed: () => reject(),
          success: () => resolveCallBack()
        });
      } else {
        resolveCallBack();
      }
    }).then(() => {
      this.saveContent();
      //发送接口
      return api.send(params);
    }).then(
        (res) => {
          if (!res.code) {
            const { snInfoMsg } = res?.data['1'] || {};
            if (snInfoMsg) {
              //额外的提示信息
              globalMethods.success({
                content: snInfoMsg,
                onOk() {
                  closeWindow();
                }
              });
              return;
            }
            closeWindow();
          }
          switch (res.code) {
            case 413:
              errHandle(
                res.data,
                (...arg) => {
                  console.log('action, data ', arg);
                  const [result] = arg || [];
                  if (!result) return;
                  //工作流事件弱校验
                  if (result.workflowEvent){
                    this.send({resolve,  weekSubmit: true});
                    this.useBaseInfo.weekSubmit = true;
                    return;
                  }
                  if (!result.isCwp) return;
                  //表单弱校验
                  this.useBaseInfo.needCheckRule = false;
                  this.send({ resolve, needCheck: false });
                  //         break;
                  // }
                },
                (err) => {
                  console.log('send error', err);
                }
              );
              // globalMethods.message.error(res.message);
              break;

            default:
              globalMethods.message.success($.i18n('meeting.send.success.alert'));

              break;
          }
        },
        (err) => {
          // globalMethods.message.error($.i18n('conference.issueRepository.send.warning') + '！');
          console.log(['err', err.stack]);
        }
      )
      .catch((e) => {
        console.log('send error!', e);
        resolve();
      })
      .finally(() => {
        resolve();
      });
  },
  saveContent() {
    //获取正文iframe对象
    const fnx = useTemplate.zwIframe.contentWindow;
    const { isCap4Forward } = useBaseInfo.baseInfo.collaborationSubmitData.colMainData;

    // 转发的表单撤销重新发送的时候
    let cap4Forward = isCap4Forward === 'true';
    const newColMainData = {
      contentZwId: fnx.contentAPI.getMainBodyData('id'),
      bodyType: cap4Forward ? '10' : fnx.contentAPI.getMainBodyData('contentType'),
      templateBodyType: cap4Forward ? '10' : fnx.contentAPI.getMainBodyData('contentType'),
      formRecordId: fnx.contentAPI.getMainBodyData('contentDataId'), // 表单
      contentSaveId: fnx.contentAPI.getMainBodyData('id'), // 正文的ID 保存待发的时候要用
      contentRightId: fnx.contentAPI.getMainBodyData('rightId'),
      // 以下两个在存个人模板的时候有用到
      contentDataId: fnx.contentAPI.getMainBodyData('contentDataId'),
      contentTemplateId: fnx.contentAPI.getMainBodyData('contentTemplateId'),
    ...(cap4Forward && {formAppid:useBaseInfo.baseInfo?.businessData?.summary?.formAppid})
    };
    useBaseInfo.setColMainData(newColMainData);
  },

  // 保存待发
  async waitSave() {
    this.saveContent();
    // let { projectId } = useBaseInfo.relatedProject;
    let moduleId = useBaseInfo.baseInfo.collaborationSubmitData.colMainData.id;
    let { systemTemplate } = useBaseInfo.baseInfo.businessData.template
      ? useBaseInfo.baseInfo.businessData.template
      : {};
    let {status, params} = await this.getCreateParams('saveAs', false, false);
    if (status === false) {
      return Promise.reject();
    }
    let colMainData = {
      subjectForCopy: ''
      // projectId: projectId, // 保存待发时需要用到的标题
    };

    let commentDeal = {
      moduleId: moduleId,
      ctype: '-1'
    };

    // 保存待发的时候如果是系统模板 置空 processID
    let workflowDefinition = {};
    if (systemTemplate) {
      workflowDefinition = {
        processId: ''
      };
    }

    // 合并数据
    params.collaborationParamData.workflowDefinition = {
      ...params.collaborationParamData.workflowDefinition,
      ...workflowDefinition
    };
    params.collaborationParamData.colMainData = {
      ...params.collaborationParamData.colMainData,
      ...colMainData
    };
    params.collaborationParamData.commentDeal = {
      ...params.collaborationParamData.commentDeal,
      ...commentDeal
    };
    let cap4 = useBaseInfo.baseInfo.zwIframe.isCap4;
    if (cap4) {
      //todo 由后端自行处理，不由前端传
      params.formParamData.data.content.needCheckRule = '0';
    }
    return api.draft(params);
  },

  // 存为模板
  async saveAsTemplate(data) {
    //提取正文id到colMainData
    this.saveContent();
    // let { projectId } = useBaseInfo.relatedProject;
    let { archiveId, prevArchiveId } = useBaseInfo.baseInfo.collaborationSubmitData.colMainData;
    let { type, subject, overId, curTemId, over, bodyId, moduleId } = data;
    let { params } = await this.getCreateParams('saveAsTemplate',false, false);
    if (params.status === false) {
      return;
    }
    let workflowDefinition = {
      processId: '-1'
    };
    let colMainData = {
      saveAsTempleteSubject: subject,
      useForSaveTemplate: 'yes',
      personTemplateId: moduleId,
      type: type,
      coverTemplateId: overId,
      checkTemplateId: curTemId,
      templateTitle: subject,
      coverState: over,
      coverTemplateBodyId: bodyId,
      // projectId: projectId,
      archiveId: archiveId, // 归档目录id
      prevArchiveId: prevArchiveId // 预归档目录id
    };
    params.collaborationParamData.workflowDefinition = {
      ...params.collaborationParamData.workflowDefinition,
      ...workflowDefinition
    };
    params.collaborationParamData.colMainData = {
      ...params.collaborationParamData.colMainData,
      ...colMainData
    };
    let cap4 = useBaseInfo.baseInfo.zwIframe.isCap4;
    if (cap4) {
      //todo 由后端自行处理，不由前端传
      params.formParamData.data.content.isMerge = '0';
      params.formParamData.data.content.needCheckRule = '0';
    }

    return api.saveAsTemplate(params);
  },

  createColMainData() {
    let { projectId } = useBaseInfo.relatedProject;
    let {
      workflowDeadLine,
      mergePolicy,
      allowOperation,
      tracks,
      supervise,
      secretLevel,
      collaborationSubmitData
    } = useBaseInfo.baseInfo;
    let { subject, importantLevel } = useBaseInfo.formInfo;

    return {
      createDate: new Date().getTime(),
      advanceRemind: workflowDeadLine.advanceRemind.value, // 提前提醒数据下拉框
      deadLineDateTime: workflowDeadLine.deadLineDateTime.value, // 流程期限为自定义时需要显示本时间框
      importantLevel: importantLevel.value, // 重要程度
      subject: subject.value, // 标题
      mergeContent: mergePolicy.mergeContent.checkedValue, // 意见
      mergeAttitude: mergePolicy.mergeAttitude.checkedValue, // 态度
      canModify: allowOperation.canModify.checked, // 是否可改变流程
      canEdit: allowOperation.canEdit.checked, // 是否可修改正文
      canEditAttachment: allowOperation.canEditAttachment.checked, // 是否可修改附件
      canArchive: allowOperation.canArchive.checked, // 是否可归档
      canForward: allowOperation.canForward.checked, // 是否可转发
      trackMemberNames:
        tracks.type === '2'
          ? tracks.appointedMembers &&
            tracks.appointedMembers.reduce((p, c) => `${p},${c.name}`, '').slice(1)
          : '',
      trackMemberIds: tracks.type === '2' ? useBaseInfo.appointedPerson : '',
      trackType: tracks.type,
      awakeDate: supervise.superviseAwakeDate, // 督办期限
      superviseTitle: supervise.superviseTitle, // 督办主题
      supervisorNames: supervise.supervisorNames, // 督办人名称，中文顿号、分割
      detailId: supervise.detailId, // 督办id, 字符串类型
      supervisorIds: supervise.supervisorIds || '', // 督办id
      unCancelledVisor: useBaseInfo.unCancelledVisor, // 不能取消的督办人
      processTermType: workflowDeadLine.processTermType.value, // 执行流程到期后的操作：流程终止还是流程撤销
      processTermTypeCheck: workflowDeadLine.isProcessTermType.checked,
      remindInterval: workflowDeadLine.remindInterval.value, // 超期后重复提醒间隔下拉框
      remindIntervalCheckBox: workflowDeadLine.isRemindInterval.checked,
      useForSaveTemplate: collaborationSubmitData.colMainData.useForSaveTemplate,
      saveAsTempleteSubject: collaborationSubmitData.colMainData.saveAsTempleteSubject,
      secretLevel: secretLevel.value, // 密级
      canStartMerge: mergePolicy.canStartMerge.checked ? mergePolicy.canStartMerge.value : '', // 处理人就是发起人
      canPreDealMerge: mergePolicy.canPreDealMerge.checked ? mergePolicy.canPreDealMerge.value : '', // 处理人和上一步相同
      canAnyDealMerge: mergePolicy.canAnyDealMerge.checked ? mergePolicy.canAnyDealMerge.value : '', // 处理人已处理过
      mergeIgnoreCommentRequired: mergePolicy.mergeIgnoreCommentRequired.checked
        ? mergePolicy.mergeIgnoreCommentRequired.value
        : '', // 忽略节点意见必填
      mergeAttitudeNull: collaborationSubmitData.colMainData.mergeAttitudeNull,
      mergeAttitudeDefault: collaborationSubmitData.colMainData.mergeAttitudeDefault,
      mergeAttitudeLast: collaborationSubmitData.colMainData.mergeAttitudeLast,
      mergeContentNull: collaborationSubmitData.colMainData.mergeContentNull,
      mergeContentLast: collaborationSubmitData.colMainData.mergeContentLast,
      formViewOperation:useBaseInfo.baseInfo?.businessData?.formData?.zwRightId||'',
      deadlineTemplate: workflowDeadLine.deadlines.value, // 流程期限
      canDeleteNode: !allowOperation.canDeleteNode.hidden && allowOperation.canDeleteNode.checked, // 是否减签时允许减掉流程模板中的固定人员
      projectId: projectId,
      ...(globalData.referType || globalData.referId) && {
        referType: globalData.referType,
        referId: globalData.referId,
      }
    };
  }
};

//各种验证
export const validate = {
  /**
   * @description: 判断事项是否可用,并且是否是重复提交。
   * @param {string} newBusiness 是否是编辑待发	1是  0不是
   * @return {Boolean}逻辑能不能继续进行
   */
  async isAffairValidAndIsLock(newBusiness) {
    const ret = callBackendMethod(
      'colManager',
      'checkAffairAndLock4NewColJson',
      this.summaryId,
      '' + newBusiness !== '1'
    );
    if (ret.code === 1) {
      globalMethods.message.error(ret.message);
      return false;
    }
    return true;
  }
};
